import React, { useState } from 'react'
import MenuConfig from '../../config'

import * as Icons from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { selectMenuList } from '../../store/reducers/tab';

const { Sider } = Layout;

// 动态获取icon
const iconToElement = (name) => React.createElement(Icons[name])

// 遍历菜单的数据
const items = MenuConfig.map(item => {
    // 没有子菜单
    const child = {
        key: item.path,
        icon: iconToElement(item.icon),
        label: item.label
    }
    // 有子菜单
    if (item.children) {
        child.children = item.children.map(subItem => {
            return {
                key: subItem.path,
                icon: iconToElement(subItem.icon),
                label: subItem.label
            }
        })
    }

    return child

})


export default function CommonAside({ isCollapse }) {
    const navigate = useNavigate()
    const dispatch = useDispatch()

    const setTabsList = (val) => {
        dispatch(selectMenuList(val))
    }

    const selectMenu = (e) => {
        let data;
        MenuConfig.forEach(item => {
            if (item.path === e.keyPath[e.keyPath.length - 1]) {
                data = item
                if (e.keyPath.length > 1) {
                    data = item.children.find(child => child.path === e.key);
                }
            }
        })
        setTabsList({
            path: data.path,
            name: data.name,
            label: data.label
        })
        navigate(e.key)
    }
    return (
        <Sider trigger={null} collapsible collapsed={isCollapse}>
            <h3 className='app-name'>{isCollapse ? '后台' : '通用后台管理系统'}</h3>
            <Menu
                theme="dark"
                mode="inline"
                defaultSelectedKeys={['1']}
                items={items}
                style={{
                    height: '100%',
                }}
                onClick={selectMenu}
            />
        </Sider>
    )
}
